package com.example.simplesrssignaling;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyWebSocketHandler extends TextWebSocketHandler {

    private final Map<String, Room> nameRootMap = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();

        ActionMessage actionMessage = objectMapper.readValue(payload, ActionMessage.class);
        String action = actionMessage.getMsg().getAction();

        switch (action) {
            case "join" -> handleJoin(actionMessage, session);
            case "publish" -> handlePublish(actionMessage, session);
            case "control" -> handleControl(actionMessage, session);
            default -> {
                // Log or send an error message for unrecognized actions.
            }
        }
    }

    private void handleJoin(ActionMessage actionMessage, WebSocketSession session) {
        String roomName = actionMessage.getMsg().getRoom();
        Room room = nameRootMap.computeIfAbsent(roomName, Room::new);

        Participant participant = new Participant();
        participant.setDisplay(actionMessage.getMsg().getDisplay());
        participant.setSession(session);
        room.add(participant);

        // Prepare response message
        var res = new HashMap<>();
        res.put("action", "join");
        res.put("room", actionMessage.getMsg().getRoom());
        res.put("self", participant); // Assuming you have a toJson method in Participant
        res.put("participants", room.getParticipants()); // Convert list of participants to JSONArray
        var message = new HashMap<>();
        message.put("msg", res);
        message.put("tid", actionMessage.getTid());
        sendMessage(session, message);

        // Notify other participants
        room.notify(session, participant, "join", actionMessage);
    }

    private void handlePublish(ActionMessage actionMessage, WebSocketSession session) {
        String roomName = actionMessage.getMsg().getRoom();
        Room room = nameRootMap.get(roomName);
        if (room != null) {
            Participant participant = room.get(actionMessage.getMsg().getDisplay());
            if (participant != null) {
                participant.setPublishing(true);

                // Notify other participants
                room.notify(session, participant, "publish", actionMessage);
            }
        }
    }

    private void handleControl(ActionMessage actionMessage, WebSocketSession session) {
        String roomName = actionMessage.getMsg().getRoom();
        Room room = nameRootMap.get(roomName);
        if (room != null) {
            Participant participant = room.get(actionMessage.getMsg().getDisplay());
            if (participant != null) {
                // You might need to handle more about control like starting a call, ending a call, etc.

                // Notify other participants
                room.notify(session, participant, "control", actionMessage);
            }
        }
    }

    @SneakyThrows
    private void sendMessage(WebSocketSession session, Object message) {
        if (!session.isOpen()) {
            return;
        }
        String jsonMessage = objectMapper.writeValueAsString(message);
        session.sendMessage(new TextMessage(jsonMessage));
    }

    // Define classes like ActionMessage, JoinResponse, and possibly more based on your needs.
    // This provided code should serve as a base structure upon which you can further build as per requirements.


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        nameRootMap.values().removeIf(room -> {
            var participants = room.getParticipants();
            for (Participant participant : participants) {
                if (session.getId().equals(participant.getSession().getId())) {
                    room.remove(participant);
                    var actionMessage = new ActionMessage();
                    room.notify(session, participant, "leave", actionMessage);
                    break;
                }
            }
            return participants.isEmpty();
        });
    }
}
